<template>
  <d2-container>
    <template slot="header">价格项-新增</template>
    <el-card shadow="never" class="d2-mb titleline">
      <div>
        <div class="mb">
          <el-button type="default" size="small" @click="addRow1">
            <d2-icon name="plus" />
            增行
          </el-button>
          <el-button
            type="default"
            size="small"
            icon="el-icon-delete"
            @click="delData1"
          >
            删行
          </el-button>
        </div>
        <el-form label-position="right" status-icon :rules="rules" :model="jgxtableData" ref="ruleForm">
        <el-table :data="jgxtableData" ref="table" tooltip-effect="dark" border stripe 
        style="width: 100%" :row-class-name="tableRow"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow1' highlight-current-row>
         <el-table-column type="selection" width="40" align="center"></el-table-column>
          <el-table-column type="index" label="序号" width="55">
          </el-table-column>
          <el-table-column label="状态" sortable width="100">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.status'" :rules="rules.status">
              <el-select
                v-model="scope.row.status"
                placeholder="请选择"
                filterable
                allow-create
              >
                <el-option label="停用" value="0"></el-option>
                <el-option label="启用" value="1"></el-option>
              </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="价格项ID" sortable>
            <template slot-scope="scope">
               <el-form-item :prop="scope.$index + '.id'" :rules="rules.id">
              <el-input class="remark" v-model="scope.row.id"></el-input>
               </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="价格项名称" sortable width="150">
            <template slot-scope="scope">
               <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
              <el-input class="remark" v-model="scope.row.name"></el-input>
               </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="价格项来源" sortable width="160">
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.price_origin'" :rules="rules.price_origin">
              <el-select
                v-model="scope.row.price_origin"
                placeholder="请选择"
                filterable
                allow-create
                @change="handle_show(scope.row.price_origin)"
              >
                <el-option label="现货行情" value="0"></el-option>
                <el-option label="期货主力合约行情" value="1"></el-option>
                <el-option label="期货合约行情" value="2"></el-option>
                <el-option label="计算项" value="3"></el-option>
                <el-option label="用户现货行情" value="4"></el-option>
              </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column label="单位" sortable>
            <template slot-scope="scope">
               <el-form-item :prop="scope.$index + '.price_unit'" :rules="rules.price_unit">
              <el-select
                v-model="scope.row.price_unit"
                placeholder="请选择"
                filterable
                allow-create
              >
               <el-option label="元（人民币）/吨" value="0"></el-option>
               <el-option label="元（人民币）/千克" value="1"></el-option>
               <el-option label="元（人民币）/桶" value="2"></el-option>     
               <el-option label="元（人民币）/立方米" value="3"></el-option>
               <el-option label="元（人民币）/张" value="4"></el-option>
               <el-option label="元（人民币）/克" value="5"></el-option>
               <el-option label="元（人民币）/500千克" value="6"></el-option>
              </el-select>
               </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="price_formula" label="定价公式" sortable width="280">
            <template slot-scope="scope">
              <div @click="DJdialog(scope.$index,scope.row)">
                     <el-input class="remark" v-model="scope.row.price_formula" placeholder="" style="width:190px;margin-right:5px;" disabled></el-input>
                    <el-button type="primary" class="dib" size="mini" plain>选择</el-button>
                  </div>
            </template>
          </el-table-column>
          <el-table-column label="备注" sortable>
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.desc'" :rules="rules.desc">
              <el-input class="remark" v-model="scope.row.desc"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
         </el-form>
      </div>
    </el-card>
    <el-button
      type="primary"
      size="mini"
      style="float: right; margin-left: 10px"
      @click="handle_JGXVisible('ruleForm')">保存</el-button>
    <!-- 定价方式 -->
      <el-dialog :visible.sync="DJdialogVisible" title="价格项计算" width="70%">
          <div class="mb" v-show="option == '3'">
          <el-button type="default" size="small" @click="addRow2">
            <d2-icon name="plus" />
            增行
          </el-button>
          <el-button
            type="default"
            size="small"
            icon="el-icon-delete"
            @click="delData2"
          >
            删行
          </el-button>
        </div>
         <el-form label-position="right" status-icon :rules="rules" :model="jgxjstableData" ref="ruleForm1">
       <el-table :data="jgxjstableData" ref="table" tooltip-effect="dark" border 
       stripe style="width: 100%" :row-class-name="tableRow"
        :cell-style="{ 'text-align': 'center' }"
        :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow2' highlight-current-row>
          <el-table-column type="selection" width="40" align="center"></el-table-column>
          <el-table-column type="index" label="序号" sortable width="75">
          </el-table-column>
          <el-table-column label="价格项来源" sortable width="350">
            <template slot-scope="scope">
               <el-form-item :prop="scope.$index + '.extra_value'" :rules="rules.extra_value">
                 <el-cascader v-model="scope.row.extra_value" :options="options" @change="handleChange(scope.$index,scope.row)" style="width:100%">
                 </el-cascader>
               </el-form-item>
            </template>
          </el-table-column>
           <el-table-column label="价格项明细" sortable width="600">
            <template slot-scope="scope">
               <el-form-item :prop="scope.$index + '.value1'" :rules="rules.value1">
                  <el-select v-model="scope.row.item" placeholder="请选择" style="width:100%;" value-key="value1">
                   <el-option v-for="item in scope.row.JGXList" :key="item.value1" :label="item.label1" :value="item">
                     <span style="float: left">{{item.label1}}</span>
                     <span style="float: right" v-show="isNaN(item.value1)">{{item.value1}}</span>
                   </el-option>
                </el-select>
               </el-form-item>
            </template>
          </el-table-column>
          
          <el-table-column label="权重" sortable>
            <template slot-scope="scope">
              <el-form-item :prop="scope.$index + '.weight'" :rules="rules.weight">
              <el-input class="remark" v-model="scope.row.weight"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
        <!-- <el-table :data="PMNameList" border highlight-current-row @current-change="handleCurrentChange_ta">
          <el-table-column type="index" :index="indexMethod" label="序号"></el-table-column>
          <el-table-column prop="status" label="状态" sortable :formatter="PMStatus"></el-table-column>
          <el-table-column prop="category" label="品类" sortable></el-table-column>
          <el-table-column prop="commodity" label="品名" sortable></el-table-column>
          <el-table-column prop="id" label="品名ID" sortable></el-table-column>
          <el-table-column prop="commodity_unit" label="商品单位" sortable :formatter="SPFormat"></el-table-column>
          <el-table-column prop="measure_unit" label="计量单位" sortable :formatter="JLFormat"></el-table-column>
          <el-table-column prop="tax_typeName" label="税种" sortable></el-table-column>
          <el-table-column prop="start_date" label="开始日期" sortable></el-table-column>
           <el-table-column prop="rate" label="税率" sortable></el-table-column>
          <el-table-column prop="brand" label="品牌" sortable></el-table-column>
          <el-table-column prop="origin" label="产地" sortable></el-table-column>
          <el-table-column prop="standard" label="规格" sortable></el-table-column>
          <el-table-column prop="attribute" label="主属性" sortable ></el-table-column>
          <el-table-column prop="desc" label="备注" sortable></el-table-column>
        </el-table> -->
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="DJChange('ruleForm1')">保存</el-button>
        </div>
      </el-dialog>
  </d2-container>
</template>
<script>
import { conPriceitem, addPriceitem, conshow } from "../../../../../../api/url_lcc";
export default {
  //商品信息-价格项-新增
  name: "priceItem_M",
  data() {
    return {
      option:"",
      a:false,
      rowNum:1,
      JGXList:[],
      // data:{ 
      //   data:'data',
      //   label:'label',
      // },
      options:[],
      jgxtableData: [{
        price_formula:""
      }],
      DJdialogVisible:false,
      djfsForm:{},
      jgxjstableData:[
        {
          extra_value:"",
          value1:"",
          weight:"",
          JGXList:[],
        }
      ],
      ruleForm:{
            status:"",
            // id: "",
            name: "",
            price_origin: "",
            price_unit: "",
            desc: ""
      },
      jgxListval:"",
      extra_value:[],
      ruleForm1:{
      //  extra_value:[],
       value:"",
       weight:"",
      },
      rules:{
        status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],
        // id: [
        //     { required: true, message: '请输入价格项ID', trigger: 'blur' },
        //   ],
        name: [
         { required: true, message: '请输入价格项名称', trigger: 'blur' },
       ],
       price_origin: [
            { required: true, message: '请选择价格项来源', trigger: 'change' }
          ],
       price_unit: [
            { required: true, message: '请选择单位', trigger: 'change' }
          ],
      //  desc: [
      //    { required: true, message: '请输入备注', trigger: 'blur' },
      //  ], 
       data: [
          { required: true, message: '请选择价格项', trigger: 'change' }
        ],
       weight: [
         { required: true, message: '请输入权重', trigger: 'blur' },
       ], 
      },
    };
  },
  methods: {
    // 价格项1
    // 联动数据
    handle_show(value){
      let params = {
        price_origin:value
        };
        conshow(params).then(res => {
              console.log(12121,res.result)
              var options = []
              this.options = res.result
              var option = res.result.length
            }).catch(err =>{
          this.$message.error(err.msg)
        });
    },
    handleChange(index,extra_value) {
      // console.log('联动数据1',extra_value,22,index,33,this.jgxjstableData[index].extra_value);
      // this.jgxjstableData[index].extra_value = extra_value
      console.log(1,extra_value); // 注意3： 最终结果是个一维数组对象
      // var val4 = extra_value.extra_value
        var val = extra_value.extra_value
        var val4=JSON.parse(JSON.stringify(val))
        console.log('index',index)
        this.handle_value(index,val4);
    },
    // 最后一级
    handle_value(index,val4){
      console.log(index,'123')
      var end = val4.pop()
      let params = {
        fr_value:val4[0],
        er_value:end
        };
        conshow(params).then(res => {
              // this.JGXList = []
              let arrys = []
                var data1 = res.result
                for (var i = 0; i < data1.length; i++) {
                        arrys[i] = {
                            value1: data1[i]['value'],
                            label1: data1[i]['label']
                        };
                    }
                    // console.log(arrys)
                this.jgxjstableData[index].JGXList=arrys
              }).catch(err =>{
          this.$message.error(err.msg);
        });
      },
    // 定价公式弹框
    DJdialog(index,row){ 
        this.DJdialogVisible = true

        // this.handle_show();
      //  this.PMNameChange();
        this.index_s=index
        console.log('价格项来源value',this.jgxtableData[this.index_s].price_origin)
        var option = this.jgxtableData[this.index_s].price_origin
        console.log('价格项来源value',option == '3')
        this.option = option
    },
    valChange(val){
    var obj = {};
    obj = this.JGXList.find(item =>{
        return item.value1 === val 
    });
    console.log(444,obj.label1)
    this.jgxjstableData[index].label1 = obj.label1
    },
      // 定价公式保存
       // 定价公式保存
    DJChange(ruleForm1,index){
      console.log('定价公式',this.jgxjstableData)
      var jgxjstableData = this.jgxjstableData
      var extra ={
        extra:{jgxjstableData}
      }
      const rule2 = new Promise((resolve, reject) => {
        this.$refs[ruleForm1].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
       Promise.all([rule2]).then(() => {
      this.DJdialogVisible = false
      console.log('定价公式保存',this.jgxjstableData,1,this.index_s)
      this.jgxtableData[this.index_s].extra = this.jgxjstableData
      console.log('价格项table',this.jgxjstableData)
      var arr = this.jgxjstableData
      for(let i = 0;i<arr.length;i++){
        console.log(12121,arr.length)
        if(arr.length === 1){
          var price_formulaAll1 = "("+(arr[0].item.label1)+")"+'*'+(arr[0].weight)
          this.jgxtableData[this.index_s].price_formula = price_formulaAll1
        }else if(arr.length === 2){
          var price_formulaAll1 = "("+(arr[0].item.label1)+")"+'*'+(arr[0].weight)+'+'+"("+(arr[1].item.label1)+")"+'*'+(arr[1].weight)
          this.jgxtableData[this.index_s].price_formula = price_formulaAll1
        }else if(arr.length === 3){
          var price_formulaAll1 = "("+(arr[0].item.label1)+")"+'*'+(arr[0].weight)+'+'+"("+(arr[1].item.label1)+")"+'*'+(arr[1].weight)+'+'+"("+(arr[2].item.label1)+")"+'*'+(arr[2].weight)
          this.jgxtableData[this.index_s].price_formula = price_formulaAll1
        }else if(arr.length === 4){
          var price_formulaAll1 = "("+(arr[0].item.label1)+")"+'*'+(arr[0].weight)+'+'+"("+(arr[1].item.label1)+")"+'*'+(arr[1].weight)+'+'+"("+(arr[2].item.label1)+")"+'*'+(arr[2].weight)+'+'+"("+(arr[3].item.label1)+")"+'*'+(arr[3].weight)
          this.jgxtableData[this.index_s].price_formula = price_formulaAll1
        }else if(arr.length === 5){
          var price_formulaAll1 = "("+(arr[0].item.label1)+")"+'*'+(arr[0].weight)+'+'+"("+(arr[1].item.label1)+")"+'*'+(arr[1].weight)+'+'+"("+(arr[2].item.label1)+")"+'*'+(arr[2].weight)+'*'+"("+(arr[3].item.label1)+")"+'*'+(arr[3].weight)+'+'+"("+(arr[4].item.label1)+")"+'*'+(arr[4].weight)
          this.jgxtableData[this.index_s].price_formula = price_formulaAll1
        }
        // console.log('arr[i]-label1',arr[i].item.label1)
        // console.log('arr[i]-weight',arr[i].weight)
        // // if(arr.length)
        // var price_formulaAll = (arr[i].item.label1)+'*'+(arr[i].weight)
        // console.log('price_formulaAll',price_formulaAll)
        // var price_formulaAll1 = price_formulaAll+'+'+price_formulaAll
        // console.log('price_formulaAll1',price_formulaAll1)
      }
      // this.jgxtableData[this.index_s].price_formula = price_formulaAll1
      console.log("价格向计算",this.jgxtableData[this.index_s].price_formula)
       });
    },
    // 新增保存
    handle_JGXVisible(ruleForm) {
      let params = {
        operation: "ADD",
        price_item: this.jgxtableData,
      };
        const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1]).then(() => {
      addPriceitem(params).then((res) => {
        // if (res.errcode === "1") {
          this.$message.success(res.result);
          // this.handle_JGX();
          this.$router.push('/basic_data/merchandise_news?table=second');
          this.closeing.closePage(this.$store.getters["d2admin/page/allPage"],this.$store.getters["d2admin/page/currentPage"])
        }).catch(err =>{
          this.$message.error(err.msg);
        });
      });
    },
    // 行内编辑
    handleCellDataChange({ rowIndex, key, value, row }) {
      console.log(rowIndex);
      console.log(key);
      console.log(value);
      console.log(row);
    },

    // 单选
    handleCurrentChange(currentRow, oldCurrentRow) {
      console.log(currentRow);
      console.log(oldCurrentRow);
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("删除1", this.multipleSelection);
    },
    // 获取表格选中时的数据
    selectRow1(val) {
      this.selectlistRow1 = val;
    },
    // 增加行
    addRow1() {
      var list = {
        rowNum: this.rowNum,
        name: "",
        status: 1,
        price_origin: "",
        price_unit: "",
        price_formula: "",
        extra:"",
        desc: "",
      };
      this.jgxtableData.push(list);
      this.rowNum += 1;
    },
    // 删除方法
    // 删除选中行
    delData1() {
      for (let i = 0; i < this.selectlistRow1.length; i++) {
        let val = this.selectlistRow1;
        val.forEach((val, index) => {
          this.jgxtableData.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.jgxtableData.splice(i, 1);
            }
          });
        });
      }
      // 删除完数据之后清除勾选框
      this.$refs.table.clearSelection();
    },

    // 获取表格选中时的数据
    selectRow2(val) {
      this.selectlistRow2 = val;
      console.log(1,this.selectlistRow2)
    },
    // 增加行
    addRow2() {
      var list = {
        rowNum: this.rowNum,
        extra_value:[],
        weight:"",
        JGXList:[]
      };
      if(this.rowNum<5){
        this.jgxjstableData.unshift(list);
      this.rowNum += 1;
      }else{
        this.$message.warning("最多只能增加5个！");
      }
      // this.jgxjstableData.push(list);
      // this.rowNum += 1;
      // alert('增加值')
      // console.log('增加值',jgxListval)
    },
    // 删除方法
    // 删除选中行
    delData2() {
      for (let i = 0; i < this.selectlistRow2.length; i++) {
        let val = this.selectlistRow2;
        val.forEach((val, index) => {
          this.jgxjstableData.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.jgxjstableData.splice(i, 1);
            }
          });
        });
      }
      // 删除完数据之后清除勾选框
      this.$refs.table.clearSelection();
    },
  },
  mounted(){
    // this.handle_show()
  }
};
</script>
